//DashboardService
define(["angularAMD"], function (angularAMD) {
    angularAMD.factory('WatchDogService', ['$rootScope', '$filter', '$translate', 'config', 'MMWService', "$http",
    function($rootScope, $filter, $translate, config, $MMWService, $http){
    	var timer;

		//呼叫getDashBoardData, 設定時間到了以後再執行callback
		//並且只有在第一次開始的時候傳入true讓loading出現
		function dashboardTimer(callback){
			watchDog.bark(watchDog.feeds, function(){
				//console.log(new Date() + ' bow-wow~ bow-wow~ ');
				timer = setTimeout(function(){
					if(callback)
						callback(callback);
				}, (watchDog.sleep||config.setting.RefreshTime)*1000);
			});
		}


    	var factory = {};
    	factory.isStart = false;

    	//看門狗
    	var watchDog = {
    		name : '',
			feed : {},       //飼料(用來保存[查詢的資料/取回的資料]的物件)
			sleep: 60,		 //睡覺(每?秒起床吠叫一次，單位為秒)
    		bark : undefined //吠叫(主要的處理用程式)
    	};
    	factory.setDog = function(dog){
    		watchDog = dog;
    	};

    	//執行dashboardTimer以呼叫getDashBoardData, 並且時間到了之後再次執行dashboardTimer
    	//並且只有在第一次開始的時候傳入true讓loading出現
    	//isDelay會讓程式延遲執行
    	factory.startWatch = function(dog, isDelay){
    		factory.isStart = true;
    		if(!timer){
    			factory.setDog(dog);
    			//20170412 add by Dustdusk for 自動登出時要同時停止WatchDog
    			$MMWService.needLogoutExtend = function(){
    				factory.stopWatch();
    			}
    			if(isDelay){
    				timer = setTimeout(function(){
    					dashboardTimer(dashboardTimer);
    				}, (dog.sleep||config.setting.RefreshTime)*1000);
    			} else {
    				dashboardTimer(dashboardTimer);
    			}
    		}
		}

    	factory.stopWatch = function(){
    		factory.isStart = false;
    		clearTimeout(timer);
    		timer = undefined;
    		//20170412 add by Dustdusk for 自動登出時要同時停止WatchDog
    		$MMWService.needLogoutExtend = undefined;
    	}

    	return factory;
    }]);
});
